import React, { FC, useEffect, useState } from 'react';
import { connect, FaqModelState } from 'umi';
import {
  Button,
  Card,
  Form,
  Input,
  Popconfirm,
  Modal,
  Select,
  Upload,
} from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import GlobalTable from '../../components/GlobalTable';
import styles from './index.less';

const { Option } = Select;

interface FaqManageProps {
  faqModel: FaqModelState;
}

const FaqManage: FC<FaqManageProps> = props => {
  const [form] = Form.useForm();
  const [form1] = Form.useForm();
  const { dispatch, faqModel }: any = props;
  const {
    faqList = [],
    pagination = {},
    categoriesList = [],
    fileList = [],
  } = faqModel;

  const [isModalVisible, setIsModalVisible] = useState(false);
  const [record, setRecord] = useState({
    id: null,
    name: undefined,
    user_type: undefined,
  });

  useEffect(() => {
    getFaqList();
  }, []);

  useEffect(() => {
    if (dispatch) {
      dispatch({
        type: 'faqModel/getCategoriesList',
        payload: {},
      });
    }
  }, []);

  const getFaqList = (params?: object | null): void => {
    if (dispatch) {
      dispatch({
        type: 'faqModel/getFaqList',
        payload: {
          ...params,
          'per-page': pagination.pageSize,
          page: pagination.current,
        },
      });
    }
  };
  const onFinish = async (values: object | null) => {
    getFaqList(values);
  };

  const onReset = () => {
    form.resetFields();
    getFaqList();
  };

  const handleDelete = (id: string) => {
    if (dispatch) {
      dispatch({
        type: 'faqModel/onDeleted',
        payload: {
          id,
        },
      });
    }
    getFaqList();
  };

  /**
   * 分页change方法
   * @param pagination
   */
  const tableChange = (pagination: object) => {
    if (dispatch) {
      dispatch({
        type: 'faqModel/tableChange',
        payload: {
          pagination,
        },
      });
    }
  };

  const showModal = (params: object | null) => {
    // @ts-ignore
    setRecord(params);
    setIsModalVisible(true);
  };

  const columns = [
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 200,
      render: (record: any) => {
        return (
          <div className={styles.opera_btn}>
            <a onClick={() => showModal(record)}>编辑</a>
            <Popconfirm
              title="确定要删除么?"
              onConfirm={() => handleDelete(record.id)}
            >
              <a>删除</a>
            </Popconfirm>
          </div>
        );
      },
    },
  ];

  const handleOk = () => {
    let payload = form1.getFieldsValue();
    if (record && record.id) {
      if (dispatch) {
        dispatch({
          type: 'faqModel/edit',
          payload: {
            ...payload,
            id: record.id,
          },
        });
      }
    } else {
      if (dispatch) {
        dispatch({
          type: 'faqModel/create',
          payload,
        });
      }
    }
    handleCancel();
  };

  const handleCancel = () => {
    // @ts-ignore
    setRecord(null);
    setIsModalVisible(false);
  };

  /**
   * 上传文件
   * @param file
   * @returns {boolean}
   */
  const beforeUpload = (file: any) => {
    if (dispatch) {
      dispatch({
        type: 'faqModel/uploadFile',
        payload: file,
      });
    }
  };

  // 移除文件
  const removeFile = () => {
    if (dispatch) {
      dispatch({
        type: 'faqModel/setFileList',
        payload: {
          fileList: [],
        },
      });
    }
  };
  return (
    <div>
      <Card bordered={false}>
        {/*  表单 */}
        <Form form={form} layout="inline" name="basic" onFinish={onFinish}>
          <Form.Item label="名称" name="name">
            <Input />
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              className={styles.submit_btn}
            >
              查询
            </Button>
            <Button onClick={onReset}>重置</Button>
          </Form.Item>
        </Form>
        {/* 新建 */}
        <div>
          <Button
            type="primary"
            className={styles.create_button}
            onClick={showModal}
          >
            新建
          </Button>
          <Upload
            name="file"
            listType="picture"
            fileList={fileList} //上传文件列表
            /*// @ts-ignore*/
            beforeUpload={file => beforeUpload(file)}
            onRemove={removeFile} //移除文件事件
          >
            <Button icon={<UploadOutlined />}>点击上传</Button>
          </Upload>
        </div>
        {/*  表格 */}
        <GlobalTable
          columns={columns}
          dataSource={faqList}
          pagination={pagination}
          onChange={tableChange}
        />
      </Card>
      {isModalVisible && (
        <Modal
          title={record && record.id ? '编辑' : '创建'}
          visible={isModalVisible}
          onOk={handleOk}
          onCancel={handleCancel}
        >
          <Form name="control-hooks" form={form1}>
            <Form.Item name="name" label="分类名称">
              <Input defaultValue={record.name} />
            </Form.Item>
            <Form.Item name="user_type" label="用户类型">
              <Select placeholder="请选择" defaultValue={record.user_type}>
                {categoriesList &&
                  categoriesList.length &&
                  categoriesList.map((item: any) => {
                    return <Option value={item.key}>{item.name}</Option>;
                  })}
              </Select>
            </Form.Item>
          </Form>
        </Modal>
      )}
    </div>
  );
};

export default connect(({ faqModel }: { faqModel: FaqModelState }) => ({
  faqModel,
}))(FaqManage);
